package com.jacklin.service.Impl;

import com.jacklin.DTO.OrderDTO;
import com.jacklin.enums.ResultEnum;
import com.jacklin.exception.MyException;
import com.jacklin.service.OrderService;
import com.jacklin.service.PayService;
import com.jacklin.utils.JsonUtil;
import com.jacklin.utils.MathUtil;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:JackLin
 * @Create 2019/3/30 10:39
 */

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private OrderService orderService;

    private static final String ORDER_NAME = "微信点餐订单";


    @Override
    public PayResponse create(OrderDTO orderDTO) {
        PayRequest payRequest = new PayRequest();
        payRequest.setOpenid(orderDTO.getBuyerOpenid());
        payRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        payRequest.setOrderId(orderDTO.getOrderId());
        payRequest.setOrderName(ORDER_NAME);
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);    //微信公众账号支付
        log.info("【微信支付】发起支付，request={}", JsonUtil.toJson(payRequest));
        PayResponse payResponse = bestPayService.pay(payRequest);
        log.info("【微信支付】发起支付，response={}", JsonUtil.toJson(payResponse));
        return payResponse;
    }

    /**
     * 微信支付异步通知
     *
     * @param notifyData
     * @return
     */
    @Override
    public PayResponse notify(String notifyData) {
        /**
         * 微信支付异步通知要注意的点:
         * 1.验证签名
         * 2.支付的状态
         * 3.验证支付金额
         * 4.支付人（下单人==支付人）好友代付，这里不做限制
         *
         * 这里的第1第2点bestPay已经帮我们实现了
         */
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("【微信支付】异步通知，payResponse", JsonUtil.toJson(payResponse));

        //修改订单的支付状态,先查询订单
        OrderDTO orderDTO = orderService.findOne(payResponse.getOrderId());

        //判断订单是否存在
        if (orderDTO == null) {
            log.error("【微信支付】异步通知，订单不存在，orderId", payResponse.getOrderId());
        }
        //3.判断金额是否一致，判断金额的方法注意前后的类型一致，比如为Decimal类型,有时候
        // 可能会将0.10和0.1认为不相等，这时候应该使用插值法来判断，比如相差小于某个值认为形象等
        if (!MathUtil.equals(orderDTO.getOrderAmount().doubleValue(), payResponse.getOrderAmount())) {
            log.error("【微信支付】异步通知，订单金额不一致,orderId={},微信通知金额={}，系统金额={}",
                    payResponse.getOrderId(), payResponse.getOrderAmount(), orderDTO.getOrderAmount());
            throw new MyException(ResultEnum.WXPAY_NOTIFY_MONEY_VERIFY_ERROR);
        }
        //4.修该订单状态
        orderService.paid(orderDTO);

        return payResponse;
    }

    /**
     * 退款
     * @param orderDTO
     * @return
     */
    @Override
    public RefundResponse refund(OrderDTO orderDTO) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderId(orderDTO.getOrderId());
        refundRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        log.info("【微信退款】request={}",JsonUtil.toJson(refundRequest));
        RefundResponse refundResponse = bestPayService.refund(refundRequest);
        log.info("【微信退款】response={}",JsonUtil.toJson(refundResponse));

        return refundResponse;
    }
}
